package org.example;

import java.awt.*;
import javax.sql.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;

/**
 * a panel that displays the content of  a result set
 */

public class DataPanel extends JPanel {
    private final java.util.List<JTextField> fields;

    /**
     * Constructs the data panel.
     * 
     * @param set the result set for a table
     * 
     * @throws SQLException when one is caught
     */

    public DataPanel(RowSet set) throws SQLException {
        fields = new ArrayList<>();
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = 1;
        gbc.gridheight = 1;

        ResultSetMetaData metaData = set.getMetaData();
        for (int i = 1; i <= metaData.getColumnCount(); i++) {
            gbc.gridy = i - 1;
            String columnName = metaData.getColumnName(i);
            gbc.gridx = 0;
            gbc.anchor = GridBagConstraints.EAST;
            add(new JLabel(columnName), gbc);

            int columnWidth = metaData.getColumnDisplaySize(i);
            JTextField tb = new JTextField(columnWidth);
            if (!set.next()) {
                String field = set.getString(i);
                if (set.wasNull()) {
                    tb.setText("NULL");
                } else {
                    tb.setText(field);
                }
            }
            fields.add(tb);
            gbc.gridx = 1;
            gbc.anchor = GridBagConstraints.WEST;
            add(tb, gbc);
        }
    }

    /**
     *
     * shows a database row
     */
    public void showRow(ResultSet resultSet){
        try {
            if(resultSet==null)return;
            for(int i=1;i<fields.size();i++){
                JTextField tb=fields.get(i-1);
                tb.setText(resultSet.getString(i));
            }
        }catch (SQLException exception){
            for(Throwable t:exception){
                System.out.println(t);
            }
        }
    }

    /**
     *Updates changed data into the current row of the row set
     */

    public void setRow(RowSet rowSet)throws SQLException{
        for(int i=1;i<=fields.size();i++){
            JTextField tb=fields.get(i-1);
            if(!rowSet.getString(i).equals(tb.getText()))
                rowSet.updateString(i,tb.getText());
            rowSet.updateRow();
        }
    }

}
